﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using System.Configuration;
using System.Collections;
using System.Web.Security;

namespace TireService.Web.View.ServiceView
{
    public partial class Completion : System.Web.UI.Page
    {

        #region Public Properties

        public List<int> MarkedServiceDetails
        {
            get
            {
                if (ViewState["_markedservicedetails"] != null)
                    return (List<int>)ViewState["_markedservicedetails"];
                else
                    return null;
            }
            set
            {
                ViewState["_markedservicedetails"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {
                //ASPxComboBox ddlContainerCargoRoom = (ASPxComboBox)gvServiceCompletion.FindEditFormTemplateControl("ddlContainerCargoRoom");
                //ddlContainerCargoRoom.DataSource 
            }

            // Bind container data to gridview
            BindServiceForCompletionData(db, DateTime.Now);

            // Change gridview pagesize based on dropdownlist
            gvServiceCompletion.SettingsPager.PageSize = Convert.ToInt32(ddlPageSize.SelectedValue);

            // Dispose connection to database
            db.Dispose();
        }

        /// <summary>
        /// Function that bind servicecarschedule that should have been completed to gridview
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="Scheduledate">Date that indicates that servicedetails should be before this date</param>
        private void BindServiceForCompletionData(TireServiceDB db, DateTime ScheduleDate)
        {
            //gvServiceCompletion.DataSource = db.ServiceCarSchedulePackingViews.Where(p => p.ScheduleDate <= ScheduleDate & p.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange & p.WorkCompleted == false).OrderBy(p => p.ScheduleDate).ToList(); - old

            gvServiceCompletion.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ScheduleDate <= ScheduleDate & p.CarId != null & p.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.ServiceDrive & p.WorkCompleted == false).OrderBy(p => p.ScheduleDate).ToList();
            //gvServiceCompletion.DataSource = db.ServiceCarScheduleDetailViews.Where(p => p.ScheduleDate <= ScheduleDate & p.CarId != null & p.ScheduleDetailTypeId == (int)Shared.ScheduleDetailType.TireChange & p.WorkCompleted == false).OrderBy(p => p.ScheduleDate).ToList(); //- temp
            gvServiceCompletion.DataBind();

            GridViewDataComboBoxColumn ddlTireSpeedIndex = gvServiceCompletion.Columns["TireSpeedIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireSpeedIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireSpeedIndex.PropertiesComboBox.DataSource = db.GetTireSpeedIndex();
            ddlTireSpeedIndex.PropertiesComboBox.TextField = "Description";
            ddlTireSpeedIndex.PropertiesComboBox.ValueField = "TireSpeedIndexId";
            ddlTireSpeedIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireSpeedIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireLoadIndex = gvServiceCompletion.Columns["TireLoadIndexDropdown"] as GridViewDataComboBoxColumn;
            ddlTireLoadIndex.PropertiesComboBox.ValueType = typeof(int);
            ddlTireLoadIndex.PropertiesComboBox.DataSource = db.GetTireLoadIndex();
            ddlTireLoadIndex.PropertiesComboBox.TextField = "Description";
            ddlTireLoadIndex.PropertiesComboBox.ValueField = "TireLoadIndexId";
            ddlTireLoadIndex.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireLoadIndex.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlTireBrand = gvServiceCompletion.Columns["TireBrandDropdown"] as GridViewDataComboBoxColumn;
            ddlTireBrand.PropertiesComboBox.ValueType = typeof(int);
            ddlTireBrand.PropertiesComboBox.DataSource = db.GetTireBrands();
            ddlTireBrand.PropertiesComboBox.TextField = "Description";
            ddlTireBrand.PropertiesComboBox.ValueField = "TireBrandId";
            ddlTireBrand.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlTireBrand.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlSize = gvServiceCompletion.Columns["SizeDropdown"] as GridViewDataComboBoxColumn;
            ddlSize.PropertiesComboBox.ValueType = typeof(decimal);
            ddlSize.PropertiesComboBox.Items.Add("8,0");
            ddlSize.PropertiesComboBox.Items.Add("9,0");
            ddlSize.PropertiesComboBox.Items.Add("10,0");
            ddlSize.PropertiesComboBox.Items.Add("12,0");
            ddlSize.PropertiesComboBox.Items.Add("13,0");
            ddlSize.PropertiesComboBox.Items.Add("14,0");
            ddlSize.PropertiesComboBox.Items.Add("15,0");
            ddlSize.PropertiesComboBox.Items.Add("16,0");
            ddlSize.PropertiesComboBox.Items.Add("17,0");
            ddlSize.PropertiesComboBox.Items.Add("17,5");
            ddlSize.PropertiesComboBox.Items.Add("18,0");
            ddlSize.PropertiesComboBox.Items.Add("19,0");
            ddlSize.PropertiesComboBox.Items.Add("20,0");
            ddlSize.PropertiesComboBox.Items.Add("21,0");
            ddlSize.PropertiesComboBox.Items.Add("22,0");
            ddlSize.PropertiesComboBox.Items.Add("23,0");
            ddlSize.PropertiesComboBox.Items.Add("24,0");
            ddlSize.PropertiesComboBox.Items.Add("48,0");
            ddlSize.PropertiesComboBox.Items.Add("390,0");
            ddlSize.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlSize.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlWidth = gvServiceCompletion.Columns["WidthDropdown"] as GridViewDataComboBoxColumn;
            ddlWidth.PropertiesComboBox.ValueType = typeof(decimal);
            ddlWidth.PropertiesComboBox.Items.Add("125,0");
            ddlWidth.PropertiesComboBox.Items.Add("135,0");
            ddlWidth.PropertiesComboBox.Items.Add("140,0");
            ddlWidth.PropertiesComboBox.Items.Add("145,0");
            ddlWidth.PropertiesComboBox.Items.Add("155,0");
            ddlWidth.PropertiesComboBox.Items.Add("165,0");
            ddlWidth.PropertiesComboBox.Items.Add("175,0");
            ddlWidth.PropertiesComboBox.Items.Add("185,0");
            ddlWidth.PropertiesComboBox.Items.Add("195,0");
            ddlWidth.PropertiesComboBox.Items.Add("205,0");
            ddlWidth.PropertiesComboBox.Items.Add("215,0");
            ddlWidth.PropertiesComboBox.Items.Add("225,0");
            ddlWidth.PropertiesComboBox.Items.Add("230,0");
            ddlWidth.PropertiesComboBox.Items.Add("235,0");
            ddlWidth.PropertiesComboBox.Items.Add("245,0");
            ddlWidth.PropertiesComboBox.Items.Add("255,0");
            ddlWidth.PropertiesComboBox.Items.Add("265,0");
            ddlWidth.PropertiesComboBox.Items.Add("275,0");
            ddlWidth.PropertiesComboBox.Items.Add("285,0");
            ddlWidth.PropertiesComboBox.Items.Add("295,0");
            ddlWidth.PropertiesComboBox.Items.Add("305,0");
            ddlWidth.PropertiesComboBox.Items.Add("315,0");
            ddlWidth.PropertiesComboBox.Items.Add("325,0");
            ddlWidth.PropertiesComboBox.Items.Add("335,0");
            ddlWidth.PropertiesComboBox.Items.Add("345,0");
            ddlWidth.PropertiesComboBox.Items.Add("375,0");
            ddlWidth.PropertiesComboBox.Items.Add("600,0");
            ddlWidth.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlWidth.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlHeight = gvServiceCompletion.Columns["HeightDropdown"] as GridViewDataComboBoxColumn;
            ddlHeight.PropertiesComboBox.ValueType = typeof(decimal);
            ddlHeight.PropertiesComboBox.Items.Add("25,0");
            ddlHeight.PropertiesComboBox.Items.Add("30,0");
            ddlHeight.PropertiesComboBox.Items.Add("35,0");
            ddlHeight.PropertiesComboBox.Items.Add("40,0");
            ddlHeight.PropertiesComboBox.Items.Add("45,0");
            ddlHeight.PropertiesComboBox.Items.Add("50,0");
            ddlHeight.PropertiesComboBox.Items.Add("55,0");
            ddlHeight.PropertiesComboBox.Items.Add("60,0");
            ddlHeight.PropertiesComboBox.Items.Add("65,0");
            ddlHeight.PropertiesComboBox.Items.Add("70,0");
            ddlHeight.PropertiesComboBox.Items.Add("75,0");
            ddlHeight.PropertiesComboBox.Items.Add("80,0");
            ddlHeight.PropertiesComboBox.Items.Add("85,0");
            ddlHeight.PropertiesComboBox.Items.Add("95,0");
            ddlHeight.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlHeight.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GridViewDataComboBoxColumn ddlRimType = gvServiceCompletion.Columns["RimTypeDropdown"] as GridViewDataComboBoxColumn;
            ddlRimType.PropertiesComboBox.ValueType = typeof(int);
            ddlRimType.PropertiesComboBox.Items.Add("Stål", 0);
            ddlRimType.PropertiesComboBox.Items.Add("Alu", 1);
            ddlRimType.PropertiesComboBox.Items.Add("Struktur", 2);
            ddlRimType.PropertiesComboBox.DropDownStyle = DropDownStyle.DropDownList;
            ddlRimType.PropertiesComboBox.IncrementalFilteringMode = IncrementalFilteringMode.StartsWith;

            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #region Private Functions

        /// <summary>
        /// Function that change grouping in order gridview
        /// </summary>
        /// <param name="ViewIndex">Integer setting the grouping mode</param>
        protected void GroupOrderData(int ViewIndex)
        {
            gvServiceCompletion.ClearSort();
            gvServiceCompletion.GroupSummary.Clear();
            switch (ViewIndex)
            {
                case 0:

                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ScheduleDate"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ContainerNumber"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ServiceCarDescription"]);

                    break;
                case 1:
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ScheduleDate"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["ContainerNumber"]);
                    gvServiceCompletion.GroupBy(gvServiceCompletion.Columns["CargoRoomNumber"]);

                    break;
            }
            gvServiceCompletion.ExpandAll();
        }

        /// <summary>
        /// Function that sends email to customer with information on completed service and with information on tire pattern
        /// </summary>
        /// <param name="CustomerEmail">Customer email that this email will be send to</param>
        /// <param name="CustomerName">Name on customer</param>
        /// <param name="SubscriptionNumber">SubscriptionNumber for customer</param>
        /// <param name="TireSetType">Tiretype description (Winther/Summer)</param>
        /// <param name="RightFront">Tirepattern on right front tire</param>
        /// <param name="LeftFront">Tirepattern on left front tire</param>
        /// <param name="RightBack">Tirepattern on right rear tire</param>
        /// <param name="LeftBack">Tirepattern on left rear tire</param>
        private void SendEmail(string CustomerEmail, string CustomerName, string SubscriptionNumber, string TireSetType, decimal RightFront, decimal LeftFront, decimal RightBack, decimal LeftBack)
        {
            string Subject = "Hjulskift gennemført - Abonnement " + SubscriptionNumber;
            bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
            Shared email = new Shared();

            Hashtable templateVars = new Hashtable();

            // Send email to customer
            templateVars.Add("CustomerName", CustomerName);
            templateVars.Add("TireSetType", TireSetType);
            templateVars.Add("RightFront", RightFront.ToString());
            templateVars.Add("LeftFront", LeftFront.ToString());
            templateVars.Add("RightBack", RightBack.ToString());
            templateVars.Add("LeftBack", LeftBack.ToString());

            decimal legaltirepattern = Convert.ToDecimal(ConfigurationManager.AppSettings["LegalTirePattern"]);

            Shared.Parser parser = new Shared.Parser();
            if (RightFront < legaltirepattern & LeftFront < legaltirepattern & RightBack < legaltirepattern & LeftBack < legaltirepattern)
            {
                // All tires are below legal interval
                parser = new Shared.Parser(Server.MapPath("~/Reports/HtmlTemplates/CustomerEmail_ServiceCompleted_NotOk.htm"), templateVars);
            }
            else
            {
                if (RightFront < legaltirepattern | LeftFront < legaltirepattern | RightBack < legaltirepattern | LeftBack < legaltirepattern)
                {
                    // One or more tires are below legal interval
                    parser = new Shared.Parser(Server.MapPath("~/Reports/HtmlTemplates/CustomerEmail_ServiceCompleted_SingleNotOk.htm"), templateVars);
                }
                else
                {
                    // All tires are within legal interval
                    parser = new Shared.Parser(Server.MapPath("~/Reports/HtmlTemplates/CustomerEmail_ServiceCompleted_Ok.htm"), templateVars);
                }
            }

            MembershipUser user = Membership.GetUser();

            email.SendEmail(CustomerEmail, ConfigurationManager.AppSettings["EmailAddress"].ToString(), parser.Parse(), Subject, true, test, user.Email, null, null);
        }


        #endregion

        #region Control Functions

        /// <summary>
        /// Button function for export of gridview
        /// </summary>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            if (ddlExport.Value == "0")
            {
                gvExport.WritePdfToResponse();
            }

            if (ddlExport.Value == "1")
            {
                gvExport.WriteXlsToResponse();
            }

            if (ddlExport.Value == "2")
            {
                gvExport.WriteCsvToResponse();
            }

            if (ddlExport.Value == "3")
            {
                gvExport.WriteRtfToResponse();
            }
        }

        /// <summary>
        /// Dropdown list function that change gridview grouping when selected item is changed
        /// </summary>
        protected void ddlView_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Group data
            GroupOrderData(Convert.ToInt32(ddlView.SelectedValue));
        }

        #endregion


        #region GridView Functions

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvServiceCompletion_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            // Format UnBoundColumn TireDimensions: Show TireDimensions
            if (e.Column.FieldName == "TireDimensions")
            {
                // Get dimensions
                string width = Convert.ToString(e.GetListSourceFieldValue("Width"));
                string height = Convert.ToString(e.GetListSourceFieldValue("Height"));
                string size = Convert.ToString(e.GetListSourceFieldValue("Size"));

                // Change field value
                e.Value = width + " / " + height + " " + size;
            }
        }

        /// <summary>
        /// Gridview function for updating servicedetail - marking for completion
        /// </summary>
        protected void gvServiceCompletion_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            try
            {
                // Get id
                int ServiceCarScheduleDetailId = Convert.ToInt32(e.Keys["ServiceCarScheduleDetailId"]);

                // Get tire pattern
                ASPxTextBox txtLF = (ASPxTextBox)gvServiceCompletion.FindEditFormTemplateControl("txtLF");
                ASPxTextBox txtLR = (ASPxTextBox)gvServiceCompletion.FindEditFormTemplateControl("txtLR");
                ASPxTextBox txtRF = (ASPxTextBox)gvServiceCompletion.FindEditFormTemplateControl("txtRF");
                ASPxTextBox txtRR = (ASPxTextBox)gvServiceCompletion.FindEditFormTemplateControl("txtRR");
                decimal LeftFrontTirePattern = Convert.ToDecimal(txtLF.Value);
                decimal LeftRearTirePattern = Convert.ToDecimal(txtLR.Value);
                decimal RightFrontTirePattern = Convert.ToDecimal(txtRF.Value);
                decimal RightRearTirePattern = Convert.ToDecimal(txtRR.Value);

                if (LeftFrontTirePattern <= 0 | LeftRearTirePattern <= 0 | RightFrontTirePattern <= 0 | RightRearTirePattern <= 0)
                {
                    throw new ArgumentException("Dækmønstre er ikke angivet korrekt");
                }

                ASPxCheckBox cbSendEmail = (ASPxCheckBox)gvServiceCompletion.FindEditFormTemplateControl("cbSendEmail");
                ASPxCheckBox cbCargoContainerRoom = (ASPxCheckBox)gvServiceCompletion.FindEditFormTemplateControl("cbCargoContainerRoom");
                ASPxTextBox txtNewCargoContainerRoom = (ASPxTextBox)gvServiceCompletion.FindEditFormTemplateControl("txtNewCargoContainerRoom");
                TextBox txtNote = (TextBox)gvServiceCompletion.FindEditFormTemplateControl("txtNote");                

                // Instantiate database connection
                TireServiceDB db = new TireServiceDB();

                // Fetch servicescheduledetail
                ServiceCarScheduleDetail detail = db.GetServiceCarScheduleDetail(ServiceCarScheduleDetailId);

                // Mark detail as completed
                detail.WorkCompleted = true;

                // Update car
                Car car = db.GetCar(Convert.ToInt32(detail.CarId));

                car.LastTireSetChangeDate = detail.ScheduleDate;
                car.NextTireSetChangePlanningDate = detail.ScheduleDate.AddMonths(4);
                car.CarStatusId = (int)Shared.CarStatus.TireChanged;

                // Fetch subscription (to see if balancing is included in customer subscription)
                CustomerSubscription subscription = db.GetCustomerSubscription(Convert.ToInt32(car.CustomerSubscriptionId));

                string subscriptionnumber = car.CustomerId.ToString() + "-" + subscription.SubscriptionId.ToString() + "-" + car.CustomerSubscriptionId.ToString();

                // Update tiresets 
                // Update from tireset
                TireSet FromTireset = db.GetTireSet(Convert.ToInt32(detail.FromTireSetId));
                TireSet ToTireset = db.GetTireSet(Convert.ToInt32(detail.ToTireSetId));

                // Create tiresetlog for fromtireset
                TireSetLogBLL bll = new TireSetLogBLL();
                bll.CreateTireSetLog(db, FromTireset, DateTime.Now, FromTireset.TireSetStatusId, (int)Shared.TireSetStatus.OnStock, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul afmonteret og lagt på lager", LeftFrontTirePattern, RightFrontTirePattern, LeftRearTirePattern, RightRearTirePattern, ToTireset.ContainerCargoRoomId);

                // Create tiresetlog for totireset
                bll.CreateTireSetLog(db, ToTireset, DateTime.Now, ToTireset.TireSetStatusId, (int)Shared.TireSetStatus.MountedOnCar, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul påmonteret kundens bil", null, null, null, null, null);

                // Placeholder properties for tiresetstatus and containercargoroomid
                int containercargoroomid = Convert.ToInt32(ToTireset.ContainerCargoRoomId);

                // Update totireset according to log
                ToTireset.TireSetStatusId = (int)Shared.TireSetStatus.MountedOnCar;
                ToTireset.ContainerCargoRoomId = null;

                // Update fromtireset according to log
                FromTireset.ContainerCargoRoomId = containercargoroomid;
                FromTireset.TireSetStatusId = (int)Shared.TireSetStatus.OnStock;
                //FromTireset.Size = Convert.ToDecimal(e.NewValues["FromSize"]);
                //FromTireset.Height = Convert.ToDecimal(e.NewValues["FromHeight"]);
                //FromTireset.Width = Convert.ToDecimal(e.NewValues["FromWidth"]);
                //FromTireset.TireSpeedIndexId = Convert.ToInt32(e.NewValues["FromTireSpeedIndexId"]);
                //FromTireset.TireLoadIndexId = Convert.ToInt32(e.NewValues["FromTireLoadIndexId"]);
                //FromTireset.TireBrandId = Convert.ToInt32(e.NewValues["FromTireBrandId"]);
                //FromTireset.TireBrandNote = Convert.ToString(e.NewValues["FromTireBrandNote"]);
                //FromTireset.LockingBolt = Convert.ToBoolean(e.NewValues["FromLockingBolt"]);
                //FromTireset.HubCaps = Convert.ToBoolean(e.NewValues["FromHubCaps"]);
                //FromTireset.RunFlatTire = Convert.ToBoolean(e.NewValues["FromRunFlatTire"]);
                //FromTireset.RimProtection = Convert.ToBoolean(e.NewValues["FromRimProtection"]);
                //FromTireset.ExtraBolts = Convert.ToBoolean(e.NewValues["FromExtraBolts"]);
                //FromTireset.RimType = Convert.ToInt32(e.NewValues["FromRimType"]);
                FromTireset.LeftFrontTirePattern = LeftFrontTirePattern;
                FromTireset.RightFrontTirePattern = RightFrontTirePattern;
                FromTireset.LeftRearTirePattern = LeftRearTirePattern;
                FromTireset.RightRearTirePattern = RightRearTirePattern;
                //FromTireset.DummyTireSet = false;
                if (subscription.BalancingIncluded) FromTireset.NeedBalancing = true;
                if (txtNote.Text != "") FromTireset.Note = txtNote.Text.ToString();

                // Check if new containercargoroom should be changed
                if (cbCargoContainerRoom.Checked)
                {
                    // Get containerid
                    int ContainerId = db.GetContainerCargoRoom(containercargoroomid).ContainerId;

                    // Get new cargo room number
                    int NewCargoRoomNumber = Convert.ToInt32(txtNewCargoContainerRoom.Text);

                    // Get new containercargoroom
                    ContainerCargoRoom room = db.ContainerCargoRooms.SingleOrDefault(p => p.ContainerId == ContainerId & p.CargoRoomNumber == NewCargoRoomNumber);

                    if (room == null)
                    {
                        throw new ArgumentException("Ny angivet lagerplads eksisterer ikke");
                    }
                    else
                    {
                        // Check if selected containercargoroom is already used
                        TireSet TireSetOccupying = db.TireSets.SingleOrDefault(p => p.ContainerCargoRoomId == room.ContainerCargoRoomId);

                        if (TireSetOccupying == null)
                        {
                            // No tireset is occupying the cargoroom already

                            // Update tireset
                            FromTireset.ContainerCargoRoomId = room.ContainerCargoRoomId;

                            // Create log
                            bll.CreateTireSetLog(db, FromTireset, DateTime.Now, FromTireset.TireSetStatusId, FromTireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, room.ContainerCargoRoomId);
                        }
                        else
                        {
                            // Other tireset occupy cargoroom - move around
                            
                            // Reset occupying tireset cargoroom
                            TireSetOccupying.ContainerCargoRoomId = null;

                            // Update tireset
                            FromTireset.ContainerCargoRoomId = room.ContainerCargoRoomId;

                            // Create log
                            bll.CreateTireSetLog(db, FromTireset, DateTime.Now, FromTireset.TireSetStatusId, FromTireset.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, room.ContainerCargoRoomId);

                            // Give occupying tireset new cargoroom
                            TireSetOccupying.ContainerCargoRoomId = containercargoroomid;

                            // Create log for occupying tireset
                            bll.CreateTireSetLog(db, TireSetOccupying, DateTime.Now, TireSetOccupying.TireSetStatusId, TireSetOccupying.TireSetStatusId, new Guid(Membership.GetUser().ProviderUserKey.ToString()), "Hjul flyttet til ny lagerplads", null, null, null, null, TireSetOccupying.ContainerCargoRoomId);
                        }
                    }
                }

                // Commit changes to database
                db.SubmitChanges();

                // Check if email should be send to customer
                if (cbSendEmail.Checked)
                {
                    // Send email to customer with information on service completion
                    Customer customer = db.GetCustomer(car.CustomerId);
                    SendEmail(customer.Email, customer.Name, subscriptionnumber, db.GetTireTypeDescription(ToTireset.TireTypeId), RightFrontTirePattern, LeftFrontTirePattern, RightRearTirePattern, LeftRearTirePattern);
                }

                // End edit mode
                e.Cancel = true;
                gvServiceCompletion.CancelEdit();

                // Refresh gridview
                BindServiceForCompletionData(db, DateTime.Now);

                // Dispose database connection
                db.Dispose();
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            
        }


        #endregion

        protected void cbCargoContainerRoom_CheckedChanged(object sender, EventArgs e)
        {
            ASPxCheckBox cbCargoContainerRoom = (ASPxCheckBox)gvServiceCompletion.FindEditFormTemplateControl("cbCargoContainerRoom");

            if (cbCargoContainerRoom.Checked)
            {
                
            }
        }

    }
}